package util

import (
	"strings"
)

//用于拼接动态查询条件结构
type SqlWhere struct {
	Fieldname string
	Value     string
	VValue    string
	IsOr      bool
	Op        string
}

// NewSqlWhere
// fieldname:  字段名称   带别名表前缀
// value    :  查询值，如果时lke 需自带百分号 %
// op       :  操作符 = > < like != <>
// isOr     :  是否为 or 条件
func NewSqlWhere(fieldname string, value string, op string, isOr bool) SqlWhere {
	return SqlWhere{Fieldname: fieldname, Value: value, VValue: "?", IsOr: isOr, Op: op}
}

// 拼接SQL条件
// sql: 不带查询条件的SQL语句，查询字段用3个井号(###)占位，方法内将用第二个参数替换,countSQL结果语句用count(1)替换
// fieldnames: 要查询的字段
// wheres: 条件Slice切片
//
//返回值 1 countSQL查询总记录数SQL语句
//      2 listSQL 查询列表SQL语句
//      3 args    查询条件，参数
func GenSql(sql string, fieldnames string, wheres []SqlWhere) (string, string, []interface{}) {
	var listSQL, countSQL = "", ""
	var args []interface{}

	for k, sw := range wheres {
		fname := sw.Fieldname
		value := sw.Value
		vvalue := sw.VValue
		isOr := sw.IsOr
		op := sw.Op

		if k > 0 {
			if isOr {
				sql += " or "
			} else {
				sql += " and "
			}
		} else {
			sql += " where "
		}
		sql += " (" + fname + " " + op + " " + vvalue + ") "
		args = append(args, value)
	}

	countSQL = strings.Replace(sql, "###", "count(1)", 1)
	listSQL = strings.Replace(sql, "###", fieldnames, 1)
	return countSQL, listSQL, args
}
